package com.woniu.service.impl;

import com.woniu.entity.Menu;
import com.woniu.mapper.MenuMapper;
import com.woniu.service.MenuService;
import com.woniu.service.RedisService;
import com.woniu.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：lisong
 * @date ：Created in 2024/2/20 16:49
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    MenuMapper menuMapper;

    @Resource
    RedisService redisService;

    @Override
    public List<Menu> queryMenu() {
        Integer userId = UserUtil.getUserInfo().getId();

        Object menuCache = redisService.getHash("menu_cache", "menu_" + userId);
        if (menuCache != null) {
            return (List<Menu>) menuCache;
        }

        List<Menu> menus = menuMapper.queryMenuByUserId(userId);

        List<Menu> menuList = menus.stream()
                .filter(menu -> menu.getParentId().equals(-1))
                .map(rootMenu -> buildMenuTree(rootMenu, menus))
                .collect(Collectors.toList());

        redisService.setHash("menu_cache", "menu_" + userId, menuList);
        return menuList;
    }

    private Menu buildMenuTree(Menu parentMenu, List<Menu> menus) {
        List<Menu> children = menus.stream()
                .filter(menu -> parentMenu.getId().equals(menu.getParentId()))
                .map(childMenu -> buildMenuTree(childMenu, menus))
                .collect(Collectors.toList());
        parentMenu.setChildrenMenu(children);
        return parentMenu;
    }


}
